<template>
  <div class="role-permission">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>角色权限分配</span>
          <el-button type="primary" @click="goBack">返回</el-button>
        </div>
      </template>

      <el-alert
        :title="'正在为角色 ' + currentRole.name + ' 分配权限'"
        type="info"
        show-icon
        :closable="false"
        class="role-info"
      />

      <!-- 权限树 -->
      <el-tree
        ref="permissionTreeRef"
        :data="permissionTree"
        show-checkbox
        node-key="id"
        :props="defaultProps"
        :default-checked-keys="defaultCheckedKeys"
        :default-expanded-keys="defaultExpandedKeys"
        @check="handleCheckChange"
        v-loading="loading"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node">
            <span>{{ data.permName }}</span>
            <span class="permission-code">({{ data.permCode }})</span>
          </span>
        </template>
      </el-tree>

      <div class="button-group">
        <el-button @click="expandAll">展开所有</el-button>
        <el-button @click="collapseAll">折叠所有</el-button>
        <el-button type="primary" @click="savePermissions">保存权限</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getRoleById, assignPermissions } from '@/api/role'
import { getAllPermissionTree, getPermissionsByRoleId } from '@/api/permission'

const route = useRoute()
const router = useRouter()

// 权限树引用
const permissionTreeRef = ref()

// 数据
const loading = ref(false)
const currentRole = reactive({
  id: '',
  name: '',
  code: '',
  description: ''
})

const permissionTree = ref([])
const defaultCheckedKeys = ref([])
const defaultExpandedKeys = ref([])

const defaultProps = {
  children: 'children',
  label: 'permName'
}

// 获取角色信息
const fetchRoleInfo = async () => {
  try {
    const response = await getRoleById(route.params.roleId)
    if (response.code === 200) {
      Object.assign(currentRole, response.data)
    } else {
      ElMessage.error(response.message || '获取角色信息失败')
    }
  } catch (err) {
    ElMessage.error('获取角色信息失败')
  }
}

// 获取权限树
const fetchPermissionTree = async () => {
  loading.value = true
  try {
    const response = await getAllPermissionTree()
    if (response.code === 200) {
      permissionTree.value = response.data
      
      // 默认展开所有节点
      const getAllNodeKeys = (nodes) => {
        const keys = []
        nodes.forEach(node => {
          keys.push(node.id)
          if (node.children && node.children.length > 0) {
            keys.push(...getAllNodeKeys(node.children))
          }
        })
        return keys
      }
      
      defaultExpandedKeys.value = getAllNodeKeys(response.data)
    } else {
      ElMessage.error(response.message || '获取权限树失败')
    }
  } catch (err) {
    ElMessage.error('获取权限树失败')
  } finally {
    loading.value = false
  }
}

// 获取角色已有的权限
const fetchRolePermissions = async () => {
  try {
    const response = await getPermissionsByRoleId(route.params.roleId)
    if (response.code === 200) {
      // 提取权限ID列表
      const permissionIds = response.data.map(permission => permission.id)
      defaultCheckedKeys.value = permissionIds
    } else {
      ElMessage.error(response.message || '获取角色权限失败')
    }
  } catch (err) {
    ElMessage.error('获取角色权限失败')
  }
}

// 处理选中变化
const handleCheckChange = (data, checkedInfo) => {
  // 可以在这里处理选中状态变化的逻辑
  console.log('选中变化:', data, checkedInfo)
}

// 展开所有节点
const expandAll = () => {
  const allKeys = []
  const getAllKeys = (nodes) => {
    nodes.forEach(node => {
      allKeys.push(node.id)
      if (node.children && node.children.length > 0) {
        getAllKeys(node.children)
      }
    })
  }
  getAllKeys(permissionTree.value)
  permissionTreeRef.value.setCheckedKeys(allKeys, false)
  permissionTreeRef.value.setExpandedKeys(allKeys)
}

// 折叠所有节点
const collapseAll = () => {
  permissionTreeRef.value.setExpandedKeys([])
}

// 保存权限分配
const savePermissions = async () => {
  try {
    const checkedKeys = permissionTreeRef.value.getCheckedKeys()
    const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
    
    // 合并选中的节点和半选中的节点
    const allCheckedKeys = [...new Set([...checkedKeys, ...halfCheckedKeys])]
    
    const response = await assignPermissions(currentRole.id, allCheckedKeys)
    if (response.code === 200) {
      ElMessage.success('权限分配成功')
    } else {
      ElMessage.error(response.message || '权限分配失败')
    }
  } catch (err) {
    ElMessage.error('权限分配失败')
  }
}

// 返回上一页
const goBack = () => {
  router.push('/system/role')
}

// 页面加载时获取数据
onMounted(() => {
  fetchRoleInfo()
  fetchPermissionTree()
  fetchRolePermissions()
})
</script>

<style scoped>
.role-permission {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.role-info {
  margin-bottom: 20px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.permission-code {
  color: #999;
  font-size: 12px;
  margin-left: 10px;
}

.button-group {
  margin-top: 20px;
  text-align: center;
}

.button-group .el-button {
  margin: 0 10px;
}
</style>